use iced::{
    Element, Task,
};
use std::collections::HashMap;
use std::time::Instant;
use crate::logging::LogEntry;

#[derive(Debug, Clone, PartialEq)]
pub enum NotificationType {
    Info,
    Warning,
    Error,
}

#[derive(Debug, Clone)]
pub struct Notification {
    pub message: String,
    pub notification_type: NotificationType,
    pub timeout: u64,
    pub shown_at: Instant,
}

#[derive(Debug, Clone, PartialEq)]
pub enum AppMode {
    Normal,
    Settings,
}

#[derive(Debug, Clone)]
pub struct TaskItem {
    pub id: usize,
    pub name: String,
    pub status: TaskStatus,
    pub current_action: Option<String>,
    pub expanded: bool,
    pub settings: HashMap<String, String>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum TaskStatus {
    Pending,
    Running,
    Finished,
    Failed,
    Stopped,
}

#[derive(Debug, Clone)]
pub enum Message {
    // 任务相关消息
    AddTask,
    SelectTask(usize),
    ToggleTaskExpanded(usize),
    StartTask(usize),
    StopTask(usize),
    SetTaskFailed(usize),

    // 设置相关消息
    ToggleSettings,
    EditSetting(String),
    UpdateSettingInput(String),
    SaveSetting(String),
    CancelEdit,

    // 注册码相关消息
    UpdateRegCode(String),
    ValidateRegCode,

    // 日志相关消息
    ToggleLogWindow,
    ScrollLogsUp,
    ScrollLogsDown,
    ClearLogs,
    ToggleLogDetailed,
    AddLog(LogEntry),

    // 其他消息
    ShowNotification(Notification),
    HideNotification,
    SetMachineCode(String),
    SetTitle(String),
    Tick,
    Exit,
}

#[derive(Default)]
pub struct App {
    pub items: Vec<TaskItem>,
    pub selected_index: Option<usize>,
    pub mode: AppMode,
    pub settings_open: bool,
    pub global_settings: HashMap<String, String>,
    pub settings_editing: Option<String>,
    pub settings_input: String,
    pub notification: Option<Notification>,
    pub title: Option<String>,
    pub machine_code: Option<String>,
    pub reg_code_input: String,
    pub logs: Vec<LogEntry>,
    pub log_window_open: bool,
    pub log_scroll: usize,
    pub log_detailed: bool,
    pub max_logs: usize,
    next_id: usize,
}

impl Default for AppMode {
    fn default() -> Self {
        AppMode::Normal
    }
}

impl App {
    pub fn new() -> (Self, Task<Message>) {
        let mut global_settings = HashMap::new();
        global_settings.insert("interval".to_string(), "5".to_string());

        let mut app = Self {
            items: Vec::new(),
            selected_index: None,
            mode: AppMode::Normal,
            settings_open: false,
            global_settings,
            settings_editing: None,
            settings_input: String::new(),
            notification: None,
            title: None,
            machine_code: None,
            reg_code_input: String::new(),
            logs: Vec::new(),
            log_window_open: false,
            log_scroll: 0,
            log_detailed: false,
            max_logs: 1000,
            next_id: 1,
        };

        // 添加初始日志条目
        app.add_startup_logs();

        // 启动初始化任务
        let init_task = Task::perform(
            async {
                match crate::utils::generate_machine_code() {
                    Ok(mc) => Message::SetMachineCode(mc),
                    Err(e) => Message::ShowNotification(Notification {
                        message: format!("无法生成机器码: {}", e),
                        notification_type: NotificationType::Error,
                        timeout: 5000,
                        shown_at: Instant::now(),
                    }),
                }
            },
            |msg| msg,
        );

        (app, init_task)
    }

    pub fn update(&mut self, message: Message) -> Task<Message> {
        match message {
            Message::AddTask => {
                self.add_task(format!("Task {}", self.next_id));
                Task::none()
            }
            Message::SelectTask(index) => {
                self.selected_index = Some(index);
                Task::none()
            }
            Message::ToggleTaskExpanded(index) => {
                if index < self.items.len() {
                    self.items[index].expanded = !self.items[index].expanded;
                }
                Task::none()
            }
            Message::StartTask(id) => {
                if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
                    item.status = TaskStatus::Running;
                    item.current_action = Some("启动中...".to_string());
                }
                Task::none()
            }
            Message::StopTask(id) => {
                if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
                    item.status = TaskStatus::Stopped;
                    item.current_action = None;
                }
                Task::none()
            }
            Message::SetTaskFailed(id) => {
                if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
                    item.status = TaskStatus::Failed;
                    item.current_action = None;
                }
                Task::none()
            }
            Message::ToggleSettings => {
                self.settings_open = !self.settings_open;
                self.mode = if self.settings_open {
                    AppMode::Settings
                } else {
                    AppMode::Normal
                };
                Task::none()
            }
            Message::EditSetting(key) => {
                self.settings_editing = Some(key.clone());
                self.settings_input = self.global_settings.get(&key).cloned().unwrap_or_default();
                Task::none()
            }
            Message::UpdateSettingInput(value) => {
                self.settings_input = value;
                Task::none()
            }
            Message::SaveSetting(key) => {
                if key == "注册码" {
                    self.reg_code_input = self.settings_input.clone();
                    if !self.reg_code_input.is_empty() {
                        return Task::perform(
                            async move { Message::ValidateRegCode },
                            |msg| msg,
                        );
                    }
                } else {
                    self.global_settings.insert(key, self.settings_input.clone());
                }
                self.settings_editing = None;
                self.settings_input.clear();
                Task::none()
            }
            Message::CancelEdit => {
                self.settings_editing = None;
                self.settings_input.clear();
                Task::none()
            }
            Message::UpdateRegCode(value) => {
                self.reg_code_input = value;
                Task::none()
            }
            Message::ValidateRegCode => {
                match crate::utils::validate_registration_code(&self.reg_code_input) {
                    Ok(expiry) => {
                        let expiry_date = format!("{}", expiry);
                        self.notification = Some(Notification {
                            message: format!("注册成功，有效期至 {}", expiry_date),
                            notification_type: NotificationType::Info,
                            timeout: 3000,
                            shown_at: Instant::now(),
                        });
                    }
                    Err(e) => {
                        self.notification = Some(Notification {
                            message: format!("注册失败: {}", e),
                            notification_type: NotificationType::Error,
                            timeout: 3000,
                            shown_at: Instant::now(),
                        });
                    }
                }
                Task::none()
            }
            Message::ToggleLogWindow => {
                self.log_window_open = !self.log_window_open;
                if self.log_window_open && !self.logs.is_empty() {
                    self.log_scroll = self.logs.len().saturating_sub(1);
                }
                self.add_app_log("日志窗口已".to_string() + if self.log_window_open { "打开" } else { "关闭" });
                Task::none()
            }
            Message::ScrollLogsUp => {
                if !self.logs.is_empty() {
                    self.log_scroll = self.log_scroll.saturating_add(1).min(self.logs.len().saturating_sub(1));
                }
                Task::none()
            }
            Message::ScrollLogsDown => {
                self.log_scroll = self.log_scroll.saturating_sub(1);
                Task::none()
            }
            Message::ClearLogs => {
                self.logs.clear();
                self.log_scroll = 0;
                self.add_app_log("日志已清空".to_string());
                Task::none()
            }
            Message::ToggleLogDetailed => {
                self.log_detailed = !self.log_detailed;
                self.add_app_log(format!("日志详细模式已{}", if self.log_detailed { "开启" } else { "关闭" }));
                Task::none()
            }
            Message::AddLog(log_entry) => {
                self.logs.push(log_entry);
                if self.logs.len() > self.max_logs {
                    self.logs.remove(0);
                    // 调整滚动位置
                    if self.log_scroll > 0 {
                        self.log_scroll = self.log_scroll.saturating_sub(1);
                    }
                }
                // 如果日志窗口打开，自动滚动到最新日志
                if self.log_window_open {
                    self.log_scroll = self.logs.len().saturating_sub(1);
                }
                Task::none()
            }
            Message::ShowNotification(notification) => {
                self.notification = Some(notification);
                Task::none()
            }
            Message::HideNotification => {
                self.notification = None;
                Task::none()
            }
            Message::SetMachineCode(machine_code) => {
                self.machine_code = Some(machine_code);
                Task::none()
            }
            Message::SetTitle(title) => {
                self.title = Some(title);
                Task::none()
            }
            Message::Tick => {
                // 检查通知是否过期
                if let Some(notification) = &self.notification {
                    if notification.shown_at.elapsed().as_millis() > notification.timeout as u128 {
                        self.notification = None;
                    }
                }
                Task::none()
            }
            Message::Exit => iced::exit(),
        }
    }

    pub fn view(&self) -> Element<Message> {
        crate::ui::view(self)
    }

    pub fn subscription(&self) -> iced::Subscription<Message> {
        iced::time::every(std::time::Duration::from_millis(100))
            .map(|_| Message::Tick)
    }

    pub fn add_task(&mut self, name: String) {
        let id = self.next_id;
        self.next_id += 1;

        let mut settings = HashMap::new();
        settings.insert("enabled".to_string(), "true".to_string());

        self.items.push(TaskItem {
            id,
            name,
            status: TaskStatus::Pending,
            current_action: None,
            expanded: false,
            settings,
        });

        if self.selected_index.is_none() && !self.items.is_empty() {
            self.selected_index = Some(0);
        }
    }

    pub fn update_task_status(&mut self, id: usize, status: TaskStatus) {
        if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
            item.status = status.clone();
            if status != TaskStatus::Running {
                item.current_action = None;
            }
        }
    }

    pub fn update_current_action(&mut self, id: usize, action: Option<String>) {
        if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
            item.current_action = action;
        }
    }

    /// 添加应用程序内部日志
    pub fn add_app_log(&mut self, message: String) {
        let log_entry = LogEntry {
            timestamp: chrono::Local::now(),
            level: "INFO".to_string(),
            module: Some("app".to_string()),
            message,
        };
        self.logs.push(log_entry);
        if self.logs.len() > self.max_logs {
            self.logs.remove(0);
        }
    }

    /// 添加启动时的日志条目
    fn add_startup_logs(&mut self) {
        let startup_logs = vec![
            ("INFO", "system", "GUI 任务管理器已启动"),
            ("INFO", "config", "全局设置已加载"),
            ("DEBUG", "ui", "用户界面初始化完成"),
            ("INFO", "app", "应用程序准备就绪"),
            ("DEBUG", "logging", "日志系统已激活"),
        ];

        for (level, module, message) in startup_logs {
            let log_entry = LogEntry {
                timestamp: chrono::Local::now(),
                level: level.to_string(),
                module: Some(module.to_string()),
                message: message.to_string(),
            };
            self.logs.push(log_entry);
        }
    }

    /// 获取可见的日志范围
    pub fn get_visible_logs(&self) -> &[LogEntry] {
        if self.logs.is_empty() {
            return &[];
        }

        let visible_count = 20.min(self.logs.len()); // 一次显示最多20条日志
        let start_idx = if self.log_scroll + visible_count >= self.logs.len() {
            self.logs.len().saturating_sub(visible_count)
        } else {
            self.logs.len().saturating_sub(self.log_scroll + visible_count)
        };
        let end_idx = (start_idx + visible_count).min(self.logs.len());

        &self.logs[start_idx..end_idx]
    }
}
